﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using LinqToVisualTree;
using System.Diagnostics;
using System.Xml.Linq;

namespace LinqToTreeWPF
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window_ContentRendered(object sender, EventArgs e)
        {

            // get all the TextBox's which have a Grid as direct parent
            var itemsFluent = this.Descendants<TextBox>()
                                  .Where(i => i.Ancestors().FirstOrDefault() is Grid);

            var itemsQuery = from v in this.Descendants<TextBox>()
                             where v.Ancestors().FirstOrDefault() is Grid
                             select v;

            // get all the StackPanels that are within another StackPanel visual tree
            var items2Fluent = this.Descendants<StackPanel>()
                                   .Descendants<StackPanel>();

            var items2Query = from i in
                                 (from v in this.Descendants<StackPanel>()                                   
                                  select v).Descendants<StackPanel>()
                              select i;

            var tree1 = this.DescendantsAndSelf().Aggregate("", (bc, n) => bc += (n.ElementsAfterSelf().Any() ? "+" : "-") + n.GetType().Name + "\n");

            // output a tree!
            string tree = this.DescendantsAndSelf().Aggregate("",
                (bc, n) => bc + n.Ancestors().Aggregate("", (ac, m) => (m.ElementsAfterSelf().Any() ? "| " : "  ") + ac,
                ac => ac + (n.ElementsAfterSelf().Any() ? "+-" : "\\-")) + n.GetType().Name + "\n");

            Debug.WriteLine(tree);
            
        }
    }
}
